package com.tywj.panda.driver.task

import android.content.Intent
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.tywj.lib.core.common.util.LogUtil
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.lib.core.common.util.ToastUtil
import com.tywj.lib.core.widget.recycleview.adapter.BaseViewHolder
import com.tywj.panda.customer.common.widget.recyclerview.MyBaseAdapter
import com.tywj.panda.driver.R
import com.tywj.panda.driver.entity.DriverTaskEntity
import com.tywj.panda.driver.service.GPSLocationService
import com.tywj.panda.driver.tool.ServiceTool


/**
 * @desc 我的订单适配器
 * @author June Yang
 * @date 2020/5/13
 * @version 2.0.0
 */
class DriverTaskAdapter : MyBaseAdapter<DriverTaskEntity.DataBean>(R.layout.driver_recycle_item_task) {

    //局部刷新
    companion object {
        const val UPDATE_TYPE_STATUS = 1
    }

    override fun convert(helper: BaseViewHolder, item: DriverTaskEntity.DataBean) {
        super.convert(helper, item)

        helper.setText(R.id.tvTime, item.lineTime)
        helper.setText(R.id.tvLineName, item.lineName)


        helper.setText(R.id.tvStatus, getStatus(item.status))

        helper.setText(
            R.id.tvNumber, "验票/乘客数: " + item.inspectTicketNum + "/" + item.assignSeateNo
        )

        if (item.punchFlag == 0) {

            if (item.startPunch == 0 && item.endPunch == 0) {
                helper.setText(R.id.tvClockStatus, "开始打卡")
            }

            if (item.startPunch == 1 && item.endPunch == 0) {
                helper.setText(R.id.tvClockStatus, "结束打卡")
                reStartService(item)
            }
            //显示打卡按钮（开始或结束按钮）
            helper.setGone(R.id.tvClockStatus, true)
            //隐藏标签
            helper.setGone(R.id.tvFlag, false)

            //服务器异常处理
            if (item.startPunch == 1 && item.endPunch == 1) {
                //隐藏打卡按钮
                helper.setGone(R.id.tvClockStatus, false)
            }
        } else {


            //隐藏打卡按钮
            helper.setGone(R.id.tvClockStatus, false)
            //显示标签
            helper.setGone(R.id.tvFlag, true)
            helper.setText(R.id.tvFlag, getFlag(item.punchFlag))
        }

        helper.addOnClickListener(R.id.tvClockStatus)
    }

    private fun getStatus(status: Int): String {

        return when (status) {
            1 -> "未发车"
            2 -> "进行中"
            else -> "已完成"
        }
    }

    //punch_flag: 打卡标记（0：未打卡，1：打卡，2：缺卡） ,
    private fun getFlag(status: Int): String {
        return when (status) {
            0 -> "未打卡"
            1 -> "已完成"
            2 -> "缺卡"
            else -> ""
        }
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {

                val position = parent.getChildLayoutPosition(view)
                if (position != RecyclerView.NO_POSITION) {
                    when (position) {
                        // 第一个
                        0 -> {
                            outRect.bottom = ResourcesUtil.getDimensionPixelSize(R.dimen.dp_10)
                            outRect.top = ResourcesUtil.getDimensionPixelSize(R.dimen.dp_10)
                        }
                        // footer
                        this@DriverTaskAdapter.data.size + this@DriverTaskAdapter.headerLayoutCount -> outRect.top = 0
                        // 其他
                        else -> outRect.bottom = ResourcesUtil.getDimensionPixelSize(com.tywj.navigation.R.dimen.dp_10)
                    }
                }
            }
        })
    }

    override fun handleLocalRefresh(
        helper: BaseViewHolder,
        item: DriverTaskEntity.DataBean,
        payloads: MutableList<Any>
    ) {
        super.handleLocalRefresh(helper, item, payloads)
        when (payloads.first().toString().toInt()) {
            UPDATE_TYPE_STATUS -> {
                updateStatus(helper, item)
            }
        }
    }

    //展开或关闭状态更新
    private fun updateStatus(helper: BaseViewHolder, item: DriverTaskEntity.DataBean) {
        if (item.status == 1) {
            helper.setText(R.id.tvClockStatus, "结束打卡")
        } else if (item.status == 2) {
            helper.setText(R.id.tvClockStatus, "打卡")
        }

        //已完成打卡 结束 隐藏
        if (item.status == 2) {
            helper.setGone(R.id.tvClockStatus, false)
        } else {
            helper.setGone(R.id.tvClockStatus, true)
        }
    }

    /**
     * 异常处理，当用户多用户登录、kill掉用户服务，再次进入当前界面时会现次启动服务
     */
    private fun reStartService(bean: DriverTaskEntity.DataBean) {

        //服务被kill掉 满足打卡进行中条件时，重启服务
        val serviceName = "com.tywj.panda.driver.service.GPSLocationService"
        if (!ServiceTool.isWorked(mContext, serviceName)) {
            val intent = Intent(mContext, GPSLocationService::class.java)
            intent.putExtra(GPSLocationService.PARAMS_BEAN, bean)
            // 中途上传中的 status为0
            intent.putExtra(GPSLocationService.PARAMS_WORK_StATUS, 0)
            mContext.startService(intent)
//            ToastUtil.shortToast("定位服务重新启动")
        } else {
            LogUtil.d("gps 服务已经启动了")
//            ToastUtil.shortToast("服务已经启动了……")
        }
    }
}